package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐（绑定了菜品信息DishId）
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto:{}", setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 按条件分页查询(优化：将套餐分类换成中文封装进SetmealDto)
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize); // 分页构造器
        //优化一：复合信息的分页构造器
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Setmeal::getName, name); //条件：按套餐名
        lqw.orderByDesc(Setmeal::getUpdateTime);//条件2：修改时间降序
        setmealService.page(pageInfo, lqw); //按条件分页查询

        //优化二：将原分页的基础数据拷贝到新分页构造器
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        //优化三：获取原分页中的套餐数据集合
        List<Setmeal> records = pageInfo.getRecords();
        //优化四：遍历套餐数据集合 得到每一个套餐
        List<SetmealDto> setmealDtoList = records.stream().map((record) -> {
            SetmealDto sd = new SetmealDto(); //准备复合对象 接收原套餐数据
            BeanUtils.copyProperties(record, sd); //拷贝过去
            //根据分页中的套餐分类的id，查到套餐分类对象

            Category category = categoryService.getById(record.getCategoryId());
            if (category != null) {
                String categoryName = category.getName(); //record套餐分类名字
                sd.setCategoryName(categoryName); //给复合对象SetmealDto的套餐分类名字赋值
            }
            return sd;//返回更新后有套餐分类名字的SetmealDto
        }).collect(Collectors.toList());

        dtoPage.setRecords(setmealDtoList);  //复合分页构造器给自己里面的集合赋值
        return R.success(dtoPage); // 返回更新后的复合分页构造器
    }


    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 批量修改状态
     *
     * @param s
     * @param ids
     * @return
     */
    @PostMapping(value = "/status/{s}")
    public R<String> updateStatus(@PathVariable int s, @RequestParam List<Long> ids) {
        log.info("s:{}", s);
        log.info("ids:{}", ids);

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        List<Setmeal> setmeals = setmealService.list(lqw).stream().map((setmeal) -> {
            setmeal.setStatus(s);
            return setmeal;
        }).collect(Collectors.toList());

        setmealService.updateBatchById(setmeals);
        return R.success("修改成功");
    }

    /**
     * 根据id查询  用于修改套餐时回显数据
     *
     * @param id
     */
    @GetMapping("/id")
    public R<SetmealDto> get(@PathVariable Long id) {
            log.info("id:{}", id);  //此时如果根据id去查询  应该是去查一个复合信息

        SetmealDto setmealDto = setmealService.getByIdWithDish(id);

        return R.success(setmealDto);
    }

    /**
     * 前端页面 查询套餐数据
     * @param setmeal
     * @return
     */
    //http://localhost:8080/setmeal/list?categoryId=1413342269393674242&status=1
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //将参数 设置成条件
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //查询并返回
        List<Setmeal> setmeals = setmealService.list(lqw);
        return R.success(setmeals);
    }

    /**
     * 修改套餐
     */
    @PutMapping
    public R<String> updateWithDish(@RequestBody SetmealDto SetmealDto){
        log.info("SetmealDto:{}",SetmealDto);
        setmealService.updateWithDish(SetmealDto);
        return R.success("修改成功");
    }

    /**
     * 移动端查看套餐详情
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> select(@PathVariable Long id){
        List<DishDto> DishDtos =  setmealService.select(id);
        return  R.success(DishDtos);
    }
}
